package com.frank.test;


import org.junit.Test;

import java.util.concurrent.*;

/**
 * Queue 先进先出
 * Deque 双向队列   可以支持FIFO形式也可以支持LIFO形式.
 * Created by zhy on 2018/7/30.
 */
public class Blocking {


    //    LinkedBlockingQueue
    //    ArrayBlockingQueue
    @Test
    public void LinkedB() throws InterruptedException {
        LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue(10);
        for (int i = 0; i < 100; i++) {
            linkedBlockingQueue.offer(i);
        }

        while (true) {
            System.out.println(linkedBlockingQueue.take());
        }
    }


    //    PriorityBlockingQueue 自动扩容，必须实现comparable
    //    DelayQueue 定时队列
    @Test
    public void DelayQ() throws InterruptedException {
        DelayQueue<Delay> delayQueue = new DelayQueue<>();
        for (int i = 0; i < 10; i++) {
            delayQueue.put(new Delay(i, i + ""));
        }

        while (true) {
            System.out.println(delayQueue.take());
        }
    }

    class Delay implements Delayed {
        long time;
        String value;

        @Override
        public String toString() {
            return value + "  " + System.currentTimeMillis();
        }

        public Delay(long time, String value) {
            this.time = time * 1000 + System.currentTimeMillis();
            this.value = value;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return time - System.currentTimeMillis();
        }

        @Override
        public int compareTo(Delayed o) {
            if (o == null || !(o instanceof Delay)) return 1;
            if (o == this) return 0;
            Delay s = (Delay) o;
            if (this.time > s.time) {
                return 1;
            } else if (this.time == s.time) {
                return 0;
            } else {
                return -1;
            }
        }
    }
}
